<template>
  <div class="app">
    <el-card style="max-width: 800px">
      <template #header>
        <div class="card-header">
          <span>登录</span>
        </div>
      </template>

      <el-form
        ref="ruleFormRef"
        style="max-width: 700px"
        :model="ruleForm"
        status-icon
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
      >
        <el-form-item label="账号" prop="username">
          <el-input v-model="ruleForm.username" type="text" autocomplete="off" />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password" type="password" autocomplete="off" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)"> 登录 </el-button>
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
let ruleFormRef = ref()

let ruleForm = reactive({})

let rules = reactive({
  username: [
    {
      trigger: 'blur',
      required: true,
      message: '请输入用户名',
    },
    {
      min: 3,
      max: 7,
      message: '请输入3-7字符',
      trigger: 'blur',
    },
  ],
  password: [
    {
      pattern: /^.{5,}$/,
      message: '密码长度至少5位且不为空字符',
      required: true,
    },
  ],
})
import { loginReq } from '../api/admin'
import { useRouter } from 'vue-router'
const router = useRouter()
const submitForm = (formEl) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      loginReq(ruleForm.username, ruleForm.password).then((res) => {
        // console.log(res.data);
        if (res.data.code == 1) {
          ElMessage.success('登录成功')
          localStorage.setItem('admin-token', res.data.data)
          router.push('/home')
        } else {
          ElMessage.error(res.data.data)
        }
      })
    }
  })
}

const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>

<style scoped lang="scss">
.app {
  background-image: url('../assets/images/bg.jpg');
  height: 100vh;
  display: flex;

  .card-header {
    text-align: center;
  }

  .el-card {
    margin: auto;
  }

  :deep(.el-form-item__content) {
    justify-content: center;
  }
}
</style>
